package com.atguigu.gulimail.cart.controller;

import com.atguigu.common.constant.CartConstant;
import com.atguigu.gulimail.cart.interceptor.CartInterceptor;
import com.atguigu.gulimail.cart.service.CartService;
import com.atguigu.gulimail.cart.vo.Cart;
import com.atguigu.gulimail.cart.vo.CartItem;
import com.atguigu.gulimail.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class CartController {
    @Autowired(required = false)
    CartService cartService;

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://gulimall.com:30001/cart.html";
    }

    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,
                            @RequestParam("num") Integer num){
        cartService.checkItemCount(skuId,num);
        return "redirect:http://gulimall.com:30001/cart.html";

    }

    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("check") Integer check){
        cartService.checkItem(skuId,check);
        return "redirect:http://gulimall.com:30001/cart.html";
    }
    @GetMapping("cart.html")
    public String cartListPage(Model model){
       //快速得到用户信息
//        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = cartService.getCart();
        model.addAttribute("cart",cart);
        return "cartList.html";
    }
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId")Long skuId, @RequestParam("num")Integer num, RedirectAttributes ra){
        cartService.addToCart(skuId,num);
        //model.addAttribute("skuId",skuId);
        //ra.addFlashAttribute()  将数据放在session里面可以在页面取出，但是只能取一次
        ra.addAttribute("skuId",skuId);//将数据放在路径后面
        return "redirect:/addToCartSuccess.html";
    }
    @GetMapping("/addToCartSuccess.html")
    //这里重定向的数据不能用redirectAttribute，原因redirectAttribute页面只能刷新一次，在刷新就没有了
    public String addToCartSuccessPage(@PathVariable("skuId") Long skuId,Model model){
        CartItem cartItem = cartService.getCartItem(skuId);
        model.addAttribute("item",cartItem);
        return "success";
    }
    @GetMapping("/currentUserCartItems")
    @ResponseBody
    public List<CartItem> getCurrentUserCartItems(){
       return cartService.getUserCartItems();
    }
}
